package com.zou.lotterylucky.activity

import android.annotation.SuppressLint
import android.app.DatePickerDialog
import android.os.Bundle
import android.widget.LinearLayout
import androidx.recyclerview.widget.LinearLayoutManager
import com.android.volley.Request
import com.android.volley.toolbox.JsonObjectRequest
import com.android.volley.toolbox.Volley
import com.google.gson.JsonArray
import com.kaopiz.kprogresshud.KProgressHUD
import com.v2.request.RequestCenter
import com.v2.utils.TToast
import com.v2.utils.okhttp.OkHttpRequestCallback
import com.zou.lotterylucky.Constants
import com.zou.lotterylucky.R
import com.zou.lotterylucky.adapters.WinningLotteryAdapter
import com.zou.lotterylucky.data.WinningLottery
import com.zou.lotterylucky.data.WinningNumber
import com.zou.lotterylucky.utils.TLog
import com.zou.lotterylucky.utils.ToastUtil
import kotlinx.android.synthetic.main.activity_login.*
import kotlinx.android.synthetic.main.activity_total.*
import kotlinx.android.synthetic.main.activity_total.topbar
import kotlinx.android.synthetic.main.activity_win_lotter.*
import org.json.JSONArray
import org.json.JSONException
import org.json.JSONObject
import java.text.SimpleDateFormat
import java.util.*

class WinLotteryActivity : BaseActivity() {

    private var cal = Calendar.getInstance()
    private lateinit var linearLayoutManager: LinearLayoutManager
    private var winningLotteryList: MutableList<WinningLottery> = mutableListOf()
    private lateinit var adapter: WinningLotteryAdapter

    @SuppressLint("WrongConstant", "SimpleDateFormat")
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        TLog.v("enter WinLotteryActivity")
        setContentView(R.layout.activity_win_lotter)

        topbar.setTitle(R.string.winning_numbers)
        topbar.addLeftBackImageButton().setOnClickListener { onBackPressed() }

        // create an OnDateSetListener
        val dateSetListener =
            DatePickerDialog.OnDateSetListener { view, year, monthOfYear, dayOfMonth ->
                cal.set(Calendar.YEAR, year)
                cal.set(Calendar.MONTH, monthOfYear)
                cal.set(Calendar.DAY_OF_MONTH, dayOfMonth)
                updateDateInView()
            }

        dateTxt.setOnClickListener {
            DatePickerDialog(
                this,
                dateSetListener,
                // set DatePickerDialog to point to today's date when it loads up
                cal.get(Calendar.YEAR),
                cal.get(Calendar.MONTH),
                cal.get(Calendar.DAY_OF_MONTH)
            ).show()
        }

        searchBtn.setOnClickListener {
            if (dateTxt.text.isEmpty()) {
                ToastUtil.showMsg(this, R.string.input_date)
                return@setOnClickListener
            }

//            val requestQueue = Volley.newRequestQueue(this)
//
//            val url = Constants.SERVER_URL + "getWinningLotteryNumbersByDate"
//            val params = JSONObject()
//            params.put("date", dateTxt.text)

            val hud = KProgressHUD.create(this).setStyle(KProgressHUD.Style.SPIN_INDETERMINATE)
                .setCancellable(true)
                .setAnimationSpeed(2)
                .setDimAmount(0.5f)
                .show()

            RequestCenter.getWinningLotteryNumbers("${dateTxt.text}", "${dateTxt.text}", -1, object : OkHttpRequestCallback {
                override fun onSuccess(result: String?) {
                    TLog.net("getWinningLotteryNumbers, result:${result}")
                    hud.dismiss()
                    val arr = JSONObject(result).getJSONArray("data")
                    if (arr.length() < 1) {
                        TToast.show("无数据，请重试")
                        return
                    }
                    val response = arr[0] as JSONObject

                    winningLotteryList = mutableListOf()
                    val winningLottery = WinningLottery(response)

                    val knumber = response.getJSONObject("knumber")
                    val ko = JSONObject()
                    ko.put("rank1_number", knumber.optString("rank1_number"))
                    ko.put("rank2_number", knumber.optString("rank2_number"))
                    ko.put("rank3_number", knumber.optString("rank3_number"))
                    winningLottery.winningNumbers.add(WinningNumber(ko))

                    val fnumber = response.getJSONObject("fnumber")
                    val fo = JSONObject()
                    fo.put("rank1_number", fnumber.optString("rank1_number"))
                    fo.put("rank2_number", fnumber.optString("rank2_number"))
                    fo.put("rank3_number", fnumber.optString("rank3_number"))
                    winningLottery.winningNumbers.add(WinningNumber(fo))

                    val dnumber = response.getJSONObject("dnumber")
                    val doo = JSONObject()
                    doo.put("rank1_number", dnumber.optString("rank1_number"))
                    doo.put("rank2_number", dnumber.optString("rank2_number"))
                    doo.put("rank3_number", dnumber.optString("rank3_number"))
                    winningLottery.winningNumbers.add(WinningNumber(doo))

                    val snumber = response.getJSONObject("snumber")
                    val so = JSONObject()
                    so.put("rank1_number", snumber.optString("rank1_number"))
                    so.put("rank2_number", snumber.optString("rank2_number"))
                    so.put("rank3_number", snumber.optString("rank3_number"))
                    winningLottery.winningNumbers.add(WinningNumber(so))

                    winningLotteryList.add(winningLottery)
                    adapter.updateAdapter(winningLotteryList)
                }

                override fun onFailure(error: String?) {
                    hud.dismiss()
                    TLog.net("getWinningHistoryByDateRange failure:$error")
                }
            })


//            val request = JsonObjectRequest(Request.Method.POST, url, params, { response ->
//                try {
//                    hud.dismiss()
//
//                    val status = response.get("status") as Int
//                    if (status == 200 && !response.isNull("data")) {
//                        val data = response.getJSONObject("data")
//
//                        winningLotteryList = mutableListOf()
//
//                        val winningLottery = WinningLottery(data)
//                        val winningNumbers = data.getJSONArray("winningNumbers")
//                        for (i in 0..3) {
//                            val winningNumber = WinningNumber(winningNumbers.getJSONObject(i))
//                            winningLottery.winningNumbers.add(winningNumber)
//                        }
//
//                        winningLotteryList.add(winningLottery)
//                        adapter.updateAdapter(winningLotteryList)
//                    } else {
//                        ToastUtil.showMsg(this, R.string.login_fail)
//                    }
//                } catch (e: JSONException) {
//                    hud.dismiss()
//                    e.printStackTrace()
//                }
//            }, { error ->
//                hud.dismiss()
//                ToastUtil.showMsg(this, R.string.login_fail)
//                error.printStackTrace()
//            })
//            requestQueue?.add(request)
        }

        updateDateInView()

        linearLayoutManager = LinearLayoutManager(this, LinearLayout.VERTICAL, false)
        numberListView.layoutManager = linearLayoutManager
        adapter = WinningLotteryAdapter(winningLotteryList)
        numberListView.adapter = adapter

        loadWinningNumbers()
    }

    private fun loadWinningNumbers() {
        TLog.v("enter loadWinningNumbers(), dateTxt.text.toString():${dateTxt.text.toString()}")
//        val requestQueue = Volley.newRequestQueue(this)
//
//        val url = Constants.SERVER_URL + "getWinningLotteryNumbersOfLast7Days"

        val hud = KProgressHUD.create(this).setStyle(KProgressHUD.Style.SPIN_INDETERMINATE)
            .setCancellable(true)
            .setAnimationSpeed(2)
            .setDimAmount(0.5f)
            .show()

        RequestCenter.getWinningLotteryNumbers("${dateTxt.text}", "${dateTxt.text}", 7, object : OkHttpRequestCallback {
            override fun onSuccess(result: String?) {
                TLog.net("getWinningLotteryNumbers, result:${result}")
                hud.dismiss()
                val arr = JSONObject(result).getJSONArray("data")
                if (arr.length() < 1) {
                    TToast.show("无数据，请重试")
                    return
                }
                val response = arr[0] as JSONObject

                winningLotteryList = mutableListOf()
                val winningLottery = WinningLottery(response)

                val knumber = response.getJSONObject("knumber")
                val ko = JSONObject()
                ko.put("rank1_number", knumber.optString("rank1_number"))
                ko.put("rank2_number", knumber.optString("rank2_number"))
                ko.put("rank3_number", knumber.optString("rank3_number"))
                winningLottery.winningNumbers.add(WinningNumber(ko))

                val fnumber = response.getJSONObject("fnumber")
                val fo = JSONObject()
                fo.put("rank1_number", fnumber.optString("rank1_number"))
                fo.put("rank2_number", fnumber.optString("rank2_number"))
                fo.put("rank3_number", fnumber.optString("rank3_number"))
                winningLottery.winningNumbers.add(WinningNumber(fo))

                val dnumber = response.getJSONObject("dnumber")
                val doo = JSONObject()
                doo.put("rank1_number", dnumber.optString("rank1_number"))
                doo.put("rank2_number", dnumber.optString("rank2_number"))
                doo.put("rank3_number", dnumber.optString("rank3_number"))
                winningLottery.winningNumbers.add(WinningNumber(doo))

                val snumber = response.getJSONObject("snumber")
                val so = JSONObject()
                so.put("rank1_number", snumber.optString("rank1_number"))
                so.put("rank2_number", snumber.optString("rank2_number"))
                so.put("rank3_number", snumber.optString("rank3_number"))
                winningLottery.winningNumbers.add(WinningNumber(so))

                winningLotteryList.add(winningLottery)
                adapter.updateAdapter(winningLotteryList)
            }

            override fun onFailure(error: String?) {
                hud.dismiss()
                TLog.net("getWinningHistoryByDateRange failure:$error")
            }
        })

//        val request = JsonObjectRequest(Request.Method.POST, url, null, { response ->
//            try {
//                hud.dismiss()
//
//                val status = response.get("status") as Int
//                if (status == 200 && !response.isNull("data")) {
//                    val data = response.getJSONArray("data")
//
//                    winningLotteryList = mutableListOf()
//
//                    for (i in 0 until data.length()) {
//                        val dataObj = data.getJSONObject(i)
//                        val winningLottery = WinningLottery(dataObj)
//                        val winningNumbers = dataObj.getJSONArray("winningNumbers")
//                        for (j in 0..3) {
//                            val winningNumber = WinningNumber(winningNumbers.getJSONObject(j))
//                            winningLottery.winningNumbers.add(winningNumber)
//                        }
//
//                        winningLotteryList.add(winningLottery)
//                    }
//
//                    adapter.updateAdapter(winningLotteryList)
//                } else {
//                    ToastUtil.showMsg(this, R.string.login_fail)
//                }
//            } catch (e: JSONException) {
//                hud.dismiss()
//                e.printStackTrace()
//            }
//        }, { error ->
//            hud.dismiss()
//            ToastUtil.showMsg(this, R.string.login_fail)
//            error.printStackTrace()
//        })
//        requestQueue?.add(request)
    }

    private fun updateDateInView() {
        val myFormat = "yyyy-MM-dd" // mention the format you need
        val sdf = SimpleDateFormat(myFormat, Locale.US)
        dateTxt.setText(sdf.format(cal.getTime()))
    }
}